package xyz.jcat.sco.admin.oauth2.server.auth;

import org.springframework.security.authentication.*;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import xyz.jcat.common.web.RespCodeMsg;
import xyz.jcat.common.web.RespException;

import java.util.Objects;

public class UserAuthenticationProvider implements AuthenticationProvider {

    private UserDetailsService userDetailsService;
    private PasswordEncoder passwordEncoder;

    public void check(UserDetails user) {
        if(Objects.isNull(user)) {
            throw new RespException(RespCodeMsg.ACCOUNT_OR_PWD_ERROR);
        }
        if(user == null) {
            throw new UsernameNotFoundException("username not found");
        }
        if (!user.isAccountNonLocked()) {
            throw new LockedException("User account is locked");
        }

        if (!user.isEnabled()) {
            throw new DisabledException("User is disabled");
        }

        if (!user.isAccountNonExpired()) {
            throw new AccountExpiredException("User account has expired");
        }

        if (!user.isCredentialsNonExpired()) {
            throw new CredentialsExpiredException("User credentials have expired");
        }
    }

    public void checkPassword(String rawPassword, String encodedPassword) {
        if(!this.passwordEncoder.matches(rawPassword, encodedPassword)) {
            throw new BadCredentialsException("Bad Credentials");
        }
    }

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        UserAuthenticationToken userAuthenticationToken = (UserAuthenticationToken) authentication;
        //TODO 验证码

        String username = userAuthenticationToken.getUsername();
        UserDetailsImpl userDetails = (UserDetailsImpl)userDetailsService.loadUserByUsername(username);
        check(userDetails);
        //密码错误
        checkPassword(userAuthenticationToken.getPassword(), userDetails.getPassword());

        return new UserAuthenticationToken(userDetails);
    }

    public UserAuthenticationProvider(UserDetailsService userDetailsService, PasswordEncoder passwordEncoder) {
        this.userDetailsService = userDetailsService;
        this.passwordEncoder = passwordEncoder;
    }

    @Override
    public boolean supports(Class<?> authentication) {
        return UserAuthenticationToken.class.isAssignableFrom(authentication);
    }
}
